import urlConfig from './config.js'
const request = {};
const headers = {
	"Content-Type": "application/json; charset=UTF-8",
	'accept': 'application/json, text/plain,*/*'
};

// 统一错误处理函数
const handleErrorMessage = (error, defaultMessage = "系统错误") => {
	const message = error?.message || (typeof error === 'string' ? error : defaultMessage);
	uni.showToast({ title: message, icon: 'none' });
	return Promise.reject(error);
};

// 创建一个请求实例
const createRequest = (url, method, data) => {

	return uni.request({
		url: urlConfig + url,
		method: method,
		data: data,
		dataType: 'json',
		header: headers
	});
};

// 请求拦截
const requestInterceptor = (url, method, data) => {
	// 可以在这里添加请求前的逻辑
	return { url, method, data };
};

// 响应拦截
const responseInterceptor = (res) => {
	const params = res.data;
	if (params.code !== 200) {
		return handleErrorMessage(params, params.message);
	}
	return params;
};

// 处理请求
request.globalRequest = async (url, method, data) => {
	// #ifdef APP-PLUS
	let proxy = plus.networkinfo.isSetProxy();
	if (proxy) {
		return handleErrorMessage("网络错误，请关闭代理后重试");
	}
	// #endif

	const { url: reqUrl, method: reqMethod, data: reqData } = requestInterceptor(url, method, data);
	try {
		const response = await createRequest(reqUrl, reqMethod, reqData);
		return responseInterceptor(response);
	} catch (error) {
		return handleErrorMessage(error);
	}
};


// 封装文件上传请求
request.uploadFile = (url, filePath, data) => {
	const token = uni.getStorageSync('token');
	return uni.uploadFile({
		url: urlConfig + url,
		filePath: filePath,
		name: 'file',
		formData: {
			...data,
			'token': token
		},
		header: {
			"Content-Type": "multipart/form-data"
		}
	}).then(res => {
		const data = JSON.parse(res.data);
		if (data.code === 200) {
			return data;
		}
		return handleErrorMessage(data, data.message);
	}).catch(err => {
		return handleErrorMessage(err, "上传失败");
	});
};

export default request;